package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zx
 * @date 2021/11/27 21:19
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 记录阅读行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult read(ReadBehaviorDTO dto) {
        log.info("开始阅读");
        // 1. 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            log.info("未获取到对象");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 查询行为实体
        ApBehaviorEntry BE = apBehaviorEntryService.findByUserIdOrEquipmentId(user==null?null:user.getId(), dto.getEquipmentId());
        if (BE == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"获取行为实体信息失败");
        }

        // 3. 查询指定文章阅读行为是否存在
        Query query = Query.query(Criteria.where("entryId").is(BE.getId()).and("articleId").is(dto.getArticleId()));

        ApReadBehavior read = mongoTemplate.findOne(query, ApReadBehavior.class);

        if(read == null){
            // 不存在  创建阅读行为
            read = new ApReadBehavior();

            read.setEntryId(BE.getId());
            read.setArticleId(dto.getArticleId());
            read.setCount((short)1); //初始化count字段值为 1
            read.setCreatedTime(new Date());
            read.setUpdatedTime(new Date());

            mongoTemplate.save(read);
        }else {
            // 存在
            read.setCount((short)(read.getCount() + 1)); //更新阅读次数
            mongoTemplate.save(read);
        }
        return ResponseResult.okResult();
    }
}
